<template>
  <el-select
    :value="value"
    filterable
    :loading="isLoading"
    value-key="code"
    multiple
    placeholder="请选择二级分类"
    clearable
    @change="handleInput"
    @clear="clear"
  >
    <el-option
      v-for="item in options"
      :key="item.code"
      :label="item.name"
      :value="item"
    />
  </el-select>
</template>

<script>
import { getSecendTagsEnums } from 'dependencies/api/application'
import LoadingMixin from 'modules/mixins/section-loading'

export default {
  mixins: [LoadingMixin],
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    value: {
      type: Array,
      default() {
        return []
      }
    },
    prop: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      options: []
    }
  },
  watch: {
    'data.cate'(val, oldValue) {
      if (val?.code && oldValue?.code && val.code === oldValue.code) return
      if (val?.code && oldValue !== undefined) {
        this.prop && this.$set(this.data, this.prop, undefined)
        this.options = []
      }
      if (!val?.code) {
        this.prop && this.$set(this.data, this.prop, undefined)
        this.options = []
        return
      }
      this.handleGetTags(val)
    }
  },
  methods: {
    async handleGetTags(value) {
      try {
        this.loading()
        const data = await getSecendTagsEnums({
          query: {
            cateId: value.code
          }
        })
        if (data.success) {
          this.options = data.data
        }
      } catch (error) {
        this.options = []
      } finally {
        this.loaded()
      }
    },
    handleInput(value) {
      if (Array.isArray(value) && value.length > 5) {
        this.$message.warning('二级分类最多只能选择五项!')
        return
      }
      this.prop && this.$set(this.data, this.prop, value)
    },
    clear() {
      this.prop && this.$set(this.data, this.prop, undefined)
    }
  }
}
</script>
